import React from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { Breadcrumb, Tooltip, Dropdown, Avatar } from 'antd';
import { BulbOutlined, FullscreenOutlined, FullscreenExitOutlined, UserOutlined } from '@ant-design/icons';
import { clearToken } from '../../utils/auth';
import './header.css';
import logo from '../../assets/phoprint-logo.svg';
import { ThemeContext } from '../../context/ThemeContext';

export default function Header() {
  const navigate = useNavigate();
  const location = useLocation();
  const { isDark, setIsDark } = React.useContext(ThemeContext);
  const [isFullscreen, setIsFullscreen] = React.useState(false);
  const [displayName, setDisplayName] = React.useState('商户A');

  React.useEffect(() => {
    try {
      const raw = localStorage.getItem('loginInfo');
      if (raw) {
        const info = JSON.parse(raw);
        if (info && info.username) setDisplayName(info.username);
      }
    } catch (e) {}
  }, []);

  function logout() {
    clearToken();
    navigate('/login');
  }

  function toggleTheme() {
    setIsDark(!isDark);
  }

  function toggleFullscreen() {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen?.().then(() => setIsFullscreen(true)).catch(() => {});
    } else {
      document.exitFullscreen?.().then(() => setIsFullscreen(false)).catch(() => {});
    }
  }

  const breadcrumbItems = (() => {
    const map = {
      '/': ['首页'],
      '/activity/collect': ['活动管理', '收藏列表'],
      '/activity/list': ['活动管理', '活动列表'],
      '/device/list': ['设备管理', '设备列表'],
      '/device/uv-models': ['设备管理', 'UV手机型号管理'],
      '/play/theme': ['玩法管理', '主题模板'],
      '/play/ai': ['玩法管理', 'AI玩法模板'],
      '/play/postcard': ['玩法管理', '明信片'],
      '/user/temp': ['用户管理', '临时用户管理'],
      '/user/temp-activity': ['用户管理', '临时用户活动'],
      '/account/wallet': ['账户管理', '钱包'],
      '/account/configuration': ['账户管理', '账户配置'],
      '/system/login-log': ['系统日志', '登录日志'],
      '/system/operation-log': ['系统日志', '操作日志'],
    };
    const segs = map[location.pathname] || ['首页'];
    const items = [];
    // 首页
    items.push({ title: <Link to="/">首页</Link> });
    if (segs.length > 1) {
      // 中间分组（不跳转）
      items.push({ title: segs[0] });
      // 当前页面
      items.push({ title: segs[1] });
    }
    return items;
  })();

  const menuProps = {
    items: [
      { key: 'profile', label: '个人资料' },
      { type: 'divider' },
      { key: 'logout', label: '退出登录' },
    ],
    onClick: ({ key }) => {
      if (key === 'profile') navigate('/account/configuration');
      if (key === 'logout') logout();
    },
  };

  return (
    <div className="header">
      <div className="brand">
        <Link to="/" className="brand-link">
          <img src={logo} alt="PhoPrint" className="brand-logo" />
          <span className="brand-name">PhoPrint</span>
        </Link>
      </div>
      <div className="breadcrumbs">
        <Breadcrumb items={breadcrumbItems} />
      </div>
      <div className="actions">
        <Link to="/">首页</Link>
        <Tooltip title={isDark ? '关闭夜间模式' : '开启夜间模式'}>
          <button className="icon-btn" onClick={toggleTheme}>
            <BulbOutlined />
          </button>
        </Tooltip>
        <Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
          <button className="icon-btn" onClick={toggleFullscreen}>
            {isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
          </button>
        </Tooltip>
        <Dropdown menu={menuProps} placement="bottomRight" trigger={["click"]}>
          <div className="avatar-box">
            <Avatar size={30} className="header-avatar" icon={<UserOutlined />} />
            <span className="user-nickname">{displayName}</span>
          </div>
        </Dropdown>
      </div>
    </div>
  );
}